<?php
/**
 * Created by PhpStorm.
 * User: lyh
 * Date: 2016/10/25
 * Time: 13:18
 */

namespace Community\Controller;
use Think\Controller;
use User\Model\UserModel;

require_once "./ThinkPHP/Library/Vendor/OSS/autoload.php";

class OfficialController extends Controller{
    public function _initialize(){
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    /**
     * 官方人员创建地区社群
     */
    public function createAssociation(){
        $title=I('title');
        $officialAddress=I('address');
        $headurl=upload(time());
        $info=array(
            'title'=>$title,
            'officialaddress'=>$officialAddress,
            'fans'=>0,
            'creatime'=>date('Y-m-d H:i',time()),
            'postcount'=>0,
            'headurl'=>$headurl,
            'summary'=>I('summary'),
        );
        M('areaassociation')->add($info);
    }

    /**
     * 用户关注地区社群
     *
     */
    public function focusAssociation(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $fakeid=I('id');
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $arr=array(
            'id'=>$id,
            'userid'=>$userid
        );
        switch($identify){
            case 'A':
                $user_asso='user_area';
                $sortasso='areaassociation';
                break;
            case 'B':
                $user_asso='user_interest';
                $sortasso='interestassociation';
                break;
        }
        $flag=M($user_asso)->add($arr);
        if($flag){
            $association=M($sortasso)->where(array('id'=>$id))->select();
            $asso=array(
               'fans'=> ++$association[0]['fans']
            );
            M($sortasso)->where(array('id'=>$id))->save($asso);
            $result=array(
                'code'=>'1',
                'message'=>'Focus Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Focus Failed!'
            );
        }
        echo json_encode($result);
    }
    /**
     * 用户取消关注地区社群
     */
    public function cancelAssociation(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $fakeid=I('id');
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['suerid'];
        $map['id']=$id;
        $map['userid']=$userid;
        switch($identify){
            case 'A':
                M('user_area')->where($map)->delete();
                break;
            case 'B':
                M('user_interest')->where($map)->delete();
                break;
        }

    }

    /**
     * 显示所有的地区社群，分页显示，每页显示5个
     *
     */
    public function showAreaAssociation(){
        $identy=I('flag');//标识  A地区  B兴趣
        $where = I('are_flag') ? ['flag'=>I('are_flag')] : 1 ;//地区的标识  C重庆 S三亚
        $p=I('page',1,'intval');//如果为空默认为0，转换成整数
        switch($identy){
            case 'A':
                $result=array();
                //只获取当前地区的
                $info=M('areaassociation')->page($p,'5')->field('id,title,headurl,summary,postcount,fans')->where($where)->select();
                for($i=0;$i<count($info);$i++)
                {
                    $arr=array(
                        'fakeid'=>'A'.$info[$i]['id'],
                        'title'=>$info[$i]['title'],
                        'headurl'=>$info[$i]['headurl'],
                        'summary'=>$info[$i]['summary'],
                        'postcount'=>$info[$i]['postcount'],
                        'fans'=>$info[$i]['fans']
                    );
                    array_push($result,$arr);
                }
                break;
            case 'B':
                $result=array();
                $info=M('interestassociation')->page($p,'5')->field('id,title,headurl,summary,postcount,fans')->select();
                for($i=0;$i<count($info);$i++)
                {
                    $arr=array(
                        'fakeid'=>'B'.$info[$i]['id'],
                        'title'=>$info[$i]['title'],
                        'headurl'=>$info[$i]['headurl'],
                        'summary'=>$info[$i]['summary'],
                        'postcount'=>$info[$i]['postcount'],
                        'fans'=>$info[$i]['fans']
                    );
                    array_push($result,$arr);
                }
                break;
        }

        echo json_encode($result,JSON_UNESCAPED_UNICODE);

    }
    /**
     * 进入社群
     */
    public function enterAssociation(){
        $fakeid=I('id');
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);

        $token=I('token');
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $map['id']=$id;
        $map['userid']=$userid;
        switch($identify){
            case 'A':
                $arr=M('user_area')->where($map)->select();
                $asso=M('areaassociation')->where(array('id'=>$id))->select();
                break;
            case 'B':
                $arr=M('user_interest')->where($map)->select();
                $asso=M('interestassociation')->where(array('id'=>$id))->select();
                break;
        }
        if($arr){ //判断关注与否
            $result=array(
                'flag'=>'1',
                'fans'=>$asso[0]['fans'],
                'headurl'=>$asso[0]['headurl'],
                'name'=>$asso[0]['title'],
                'post'=>$asso[0]['postcount']

            );
        }
        else {
            if ($token == '') {
                $result = array(
                    'flag' => '0',
                    'fans' => $asso[0]['fans'],
                    'headurl' => $asso[0]['headurl'],
                    'name' => $asso[0]['title'],
                    'post'=>$asso[0]['postcount'],
                    'code' => '3'
                );
            } else {
                $result = array(
                    'flag' => '0',
                    'fans' => $asso[0]['fans'],
                    'headurl' => $asso[0]['headurl'],
                    'name' => $asso[0]['title'],
                    'post'=>$asso[0]['postcount']
                );
            }
        }
        echo json_encode($result);
    }

    /**
     *执行帖子图片上传
     * Parameter：name, falg  //判断属于地区社群还是兴趣社群
     * return :id,返回上传成功的id编号
     */
    public function uploadPicture(){
        $pictureName=I('name');
        $flag=I('flag');
        $url = upload($pictureName,'community'.$flag);//获取存入的地址
        //如果图片没有上传成功直接返回
        if (empty($url)){
            $result = [
                'id'=>'',
                'status'=>0,
            ];
            echo json_encode($result);
            exit;
        }
        //构建入库数据
        $data = array(
            'url'=>$url,
            'flag'=>$flag
        );
        //将地址存入相应的表格中
        $id = M('pic_post')->add($data);
        $result = [
            'id'=>$id ? $id : '',
            'status'=>$id ? 1 : 0,
        ];
        $this->ajaxReturn($result);
    }

    /**
     *社群发帖
     */
    public function doAreaPost(){
        $title=I('title');
        $content=I('content');
        if(empty($title) || empty($content)){
            echo json_encode(['code'=>'0','message'=>'error']);
            return;
        }
        $pic=I('pic');//图片数组
        $fakeid=I('id');
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $userdetail=M('userdetail')->where(array('token'=>$token))->select();
        $username=$userdetail[0]['username'];
        $headurl=$userdetail[0]['headurl'];
        $data=array(
            'userid'=>$userid,
            'pid'=>$id,
            'content'=>$content,
            'summary'=>substr($content,0,15),
            'username'=>$username,
            'headurl'=>$headurl,
            'title'=>$title,
            'time'=>date('Y-m-d H:i',time())
        );
        switch($identify){
            case 'A':
                //将发帖数+1
                $asso=M('areaassociation')->where(array('id'=>$id))->select();
                $assoUpdate=array(
                    'postcount'=>++$asso[0]['postcount']
                );
                M('areaassociation')->where(array('id'=>$id))->save($assoUpdate);
                $pid=M('areapost')->add($data);
                //循环把图片关联存入表中
                $pic_post = M('pic_post');
                foreach ($pic as $item){
                    $pic_post->where(['id'=>$item])->save(['flag'=>'A'.$pid]);
                }
                $this->ajaxReturn(['username'=>$username]);
                break;
            case 'B':
                $asso=M('interestassociation')->where(array('id'=>$id))->select();
                $assoUpdate=array(
                    'postcount'=>++$asso[0]['postcount']
                );
                M('interestassociation')->where(array('id'=>$id))->save($assoUpdate);
                $pid=M('interestpost')->add($data);
                //循环把图片关联存入表中
                $pic_post = M('pic_post');
                foreach ($pic as $item){
                    $pic_post->where(['id'=>$item])->save(['flag'=>'B'.$pid]);
                }
                $this->ajaxReturn(['username'=>$username]);
                break;
        }
    }
    /**
     * 显示社群里面的帖子列表
     */
    public function showAreaPostList(){
        $fakeid=I('id');//社群id
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $p=I('page',1,'intval');//如果为空默认为0，转换成整数

        $picPost = M('pic_post');
        //A为地区，B为兴趣
        switch($identify){
            case 'A':
                $result=array();
                $info=M('areapost')->join('left join __USERDETAIL__ u on __AREAPOST__.userid=u.userid')->where(array('pid'=>$id))->page($p,'5')->field('id,title,u.headurl,summary,commentcount,time,u.username')->order('time desc')->select();
                foreach ($info as $k=>$item){
                    //获取图片地址
                    $pic_url = $picPost->where(array('flag'=>'A'.$item['id']))->getField('url',true);
                    $arr=array(
                        'fakeid'=>'A'.$item['id'],
                        'title'=>$item['title'],
                        'headurl'=>$item['headurl'],
                        'summary'=>$item['summary'],
                        'commentcount'=>$item['commentcount'],
                        'time'=>$item['time'],
                        'username'=>$item['username'],
                        'pic'=>$pic_url ? $pic_url : [],
                    );
                    array_push($result,$arr);
                }
                break;
            case 'B':
                $result=array();
                $info = M('interestpost')->join('left join __USERDETAIL__ u on __INTERESTPOST__.userid=u.userid')->where(array('pid'=>$id))->where(array('pid'=>$id))->page($p,'5')->field('id,title,u.headurl,summary,commentcount,time,u.username')->order('time desc')->select();
                foreach ($info as $k=>$item){
                    //获取图片地址
                    $pic_url = $picPost->where(array('flag'=>'B'.$item['id']))->getField('url',true);
                    $arr=array(
                        'fakeid'=>'B'.$item['id'],
                        'title'=>$item['title'],
                        'headurl'=>$item['headurl'],
                        'summary'=>$item['summary'],
                        'commentcount'=>$item['commentcount'],
                        'time'=>$item['time'],
                        'username'=>$item['username'],
                        'pic'=>$pic_url ? $pic_url : [],
                    );
                    array_push($result,$arr);
                }
                break;
        }

        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 给帖子添加评论
     */
    public function doAreaComment(){
        $fakeid=I('id');
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $content=I('content');
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $userdetail=M('userdetail')->where(array('token'=>$token))->select();
        $username=$userdetail[0]['username'];
        $headurl=$userdetail[0]['headurl'];
        $data=array(
            'pid'=>$id,
            'time'=>date('Y-m-d H:i',time()),
            'content'=>$content,
            'username'=>$username,
            'headurl'=>$headurl,
            'userid'=>$userid
        );
        switch($identify)
        {
            case 'A':
                $post=M('areapost')->where(array('id'=>$id))->select();
                M('areacomment')->add($data);
                $update=array(
                    'commentcount'=>++$post[0]['commentcount']
                );
                M('areapost')->where(array('id'=>$id))->save($update);
                break;
            case 'B':
                $post=M('interestpost')->where(array('id'=>$id))->select();
                M('interestcomment')->add($data);
                $update=array(
                    'commentcount'=>++$post[0]['commentcount']
                );
                M('interestpost')->where(array('id'=>$id))->save($update);
                break;
        }

    }

    /**
     * 显示帖子的详情加评论,评论分页显示
     */
    public function showAreaPostDetail(){
        $fakeid=I('id');//帖子id
        $identify=substr($fakeid,0,1);//属于什么身份
        $id=substr($fakeid,1);
        $p=I('page',1,'intval');//如果为空默认为0，转换成整数
        //获取帖子图片
        $pic=M('pic_post')->where(array('flag'=>$fakeid))->getField('url',true);
        switch($identify){
            case 'A':
                $post=M('areapost')->where(array('id'=>$id))->field('id,username,headurl,title,time,summary,content')->select();
                $comment=M('areacomment')->where(array('pid'=>$post[0]['id']))->page($p,'3')->field('time,headurl,username,content')->select();
                $result=array(
                    'post'=>$post,
                    'pic'=>$pic ? $pic : [],
                    'comment'=>$comment
                );
                break;
            case 'B':
                $post=M('interestpost')->where(array('id'=>$id))->field('id,username,headurl,title,time,summary,content')->select();
                $comment=M('interestcomment')->where(array('pid'=>$post[0]['id']))->page($p,'3')->field('time,headurl,username,content')->select();
                $result=array(
                    'post'=>$post,
                    'pic'=>$pic ? $pic : [],
                    'comment'=>$comment
                );
                break;
        }

        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 社群模块的搜索接口
     */
    public function search(){
        $content=I('content');
        if($content==''){
            return null;
        }
        $namemap['title']=array('like',"%".$content."%");
        $result=array();
        $a=M('areaassociation')->where($namemap)->select();
        for ($i=0;$i<count($a);$i++)
        {
            $data=array(
                'name'=>$a[$i]['title'],
                'id'=>'A'.$a[$i]['id']
            );
            array_push($result,$data);//把内容添加到数组中
        }
        $b=M('interestassociation')->where($namemap)->select();
        for ($i=0;$i<count($b);$i++)
        {
            $data=array(
                'name'=>$b[$i]['title'],
                'id'=>'B'.$b[$i]['id']
            );
            array_push($result,$data);//把内容添加到数组中
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 社群地区删帖 只限本人删除
     */
    public function delteCardToAre($id,$token){
        //调用删帖方法
        $this->ajaxReturn($this->_deleteCard($id,$token,'A','areacomment','areapost','areaassociation'));
    }
    /**
     * 社群兴趣删帖 只限本人删除
     */
    public function delteCardToInterest($id,$token){
        //调用删帖
        $this->ajaxReturn($this->_deleteCard($id,$token,'B','interestcomment','interestpost','interestassociation'));
    }

    /**
     * 地区和兴趣的删帖 只限本人删除
     * @param $id //帖子id
     * @param $taken //用户token
     * @param $table //对应表
     * @param $commentTable //评论表
     * @param $flag //标识  A为地区B为兴趣
     * @param $ptable //地区或者兴趣表
     * @return array //返回删除返回信息
     */
    private function _deleteCard($id,$token,$flag,$commentTable,$table,$ptable){
        //根据token获取当前用户的id
        $user_model = new UserModel();
        $user_id = $user_model->getIdByToken($token);
        //获取贴子详情
        $post_info = M($table)->where(['id'=>$id])->find();
        //判断当前贴子是否为本人发的
        if($post_info['userid'] == $user_id){
            //删除对应pic_post的图片表
            M('pic_post')->where(['flag'=>$flag.$id])->delete();
            //删除评论
            M($commentTable)->where(['pid'=>$id])->delete();
            $res = [];
            if(M($table)->where(['id'=>$id])->delete()){
                //将地区或者兴趣表的帖子统计-1
                M($ptable)->where(['id'=>$post_info['pid']])->setDec('postcount');
                $res = ['code'=>1,];
            }else{
                $res = ['code'=>0,];
            }
        }else{
            $res = ['code'=>0,];
        }
        return $res;
    }

    /**
     * 获取热贴 6个地区贴
     * @param are_flag //地区标识
     */
    public function getHotPost(){
        $where = I('are_flag') ? ['flag'=>I('are_flag')] : 1 ;//地区的标识  C重庆 S三亚
        //获取当前地区的所有id
        $are_ids = M('areaassociation')->where($where)->getField('id',true);
        $are_posts = M('areapost')->field('id,title,headurl,summary,commentcount,time,username')->where(['pid'=>['in',$are_ids?$are_ids:'']])->order('id desc')->limit(3)->select();
        $picPost = M('picPost');
        $result = [];
        foreach ($are_posts as $item){
            //获取地区 图片地址
            $pic_url = $picPost->where(['flag'=>'A'.$item['id']])->getField('url',true);
            $arr=array(
                'fakeid'=>'A'.$item['id'],
                'title'=>$item['title'],
                'headurl'=>$item['headurl'],
                'summary'=>$item['summary'],
                'commentcount'=>$item['commentcount'],
                'time'=>$item['time'],
                'username'=>$item['username'],
                'pic'=>$pic_url ? $pic_url : [],
            );
            array_push($result,$arr);
        }
        $this->ajaxReturn($result);
    }
}
